package com.wing.wcabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.CellInventoryInoutDetailForm;
import com.wing.cabinet.model.request.UseInventoryInoutDetailForm;
import com.wing.common.exception.BusinessException;
import com.wing.order.service.DynamicService;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import com.wing.wcabinet.dao.WcabUseInventoryInoutDetailDao;
import com.wing.wcabinet.model.entity.*;
import com.wing.wcabinet.model.request.WcabCellInventoryInoutDetailForm;
import com.wing.wcabinet.model.request.WcabUseInventoryInoutDetailForm;
import com.wing.wcabinet.model.response.WcabUseInventoryInoutDetailVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 售刀柜领取/暂存柜上/暂存/维修/回收明细-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class WcabUseInventoryInoutDetailServiceImpl extends ServiceImpl<WcabUseInventoryInoutDetailDao, WcabUseInventoryInoutDetail> implements WcabUseInventoryInoutDetailService {

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private WcabUseInventoryProductService inventoryProductService;


    @Autowired
    private WcabUseInventoryUserService inventoryUserService;

    @Autowired
    private WcabUseInventoryInoutService inventoryInoutService;

    @Autowired
    private ProductDetailService productDetailService;


    @Override
    public int add(WcabUseInventoryInoutDetailForm wcabUseInventoryInoutDetailForm) {

        //校验

        WcabUseInventoryInoutDetail wcabUseInventoryInoutDetail =new WcabUseInventoryInoutDetail();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WcabUseInventoryInoutDetail.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(wcabUseInventoryInoutDetailForm, wcabUseInventoryInoutDetail, copyOptions);

        return baseMapper.insert(wcabUseInventoryInoutDetail);
    }

    @Override
    public List<WcabUseInventoryInoutDetailVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<WcabUseInventoryInoutDetailVO> pageList4app(Page page, Map<String, Object> params) {
        List<WcabUseInventoryInoutDetailVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WcabUseInventoryInoutDetailVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public WcabUseInventoryInout inventoryIn(List<WcabCellInventoryInoutDetailForm> list, Long cellInventoryInoutId, WcabCellInventoryInout.BusinessType businessType, String deviceCode, String orderCode) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        WcabUseInventoryInout wcabUseInventoryInout=new WcabUseInventoryInout();
        String code=dynamicService.getDayNextCode("cab_use_inventory_inout");
        String day=simpleDateFormat.format(new Date());
        wcabUseInventoryInout.setCode("IN-"+day+"-"+code);
        wcabUseInventoryInout.setDay(Integer.valueOf(day));
        wcabUseInventoryInout.setNo(Integer.valueOf(code));
        wcabUseInventoryInout.setCreator(JwtUtils.getLoginUserId());
        wcabUseInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        wcabUseInventoryInout.setInoutType(WcabUseInventoryInout.InoutType.in);
        wcabUseInventoryInout.setBusinessType(WcabUseInventoryInout.BusinessType.jsonCreator(businessType.name()));
        wcabUseInventoryInout.setRemark(businessType.getDesc());
        wcabUseInventoryInout.setBusinessId(cellInventoryInoutId);
        wcabUseInventoryInout.setDeviceCode(deviceCode);
        wcabUseInventoryInout.setOrderCode(orderCode);
        wcabUseInventoryInout.setCellInventoryInoutId(cellInventoryInoutId);
        inventoryInoutService.save(wcabUseInventoryInout);
        saveDetail(list,wcabUseInventoryInout.getId(),UseInventoryInout.Type.in.name(),businessType.name(),deviceCode,orderCode,cellInventoryInoutId,null, StorageInventoryInout.BusinessDetailType.jsonCreator(businessType.name()));
//        wcabUseInventoryInout.setLabelCodeList(labelCodes);
        return wcabUseInventoryInout;
    }

    @Override
    @Transactional
    public void inventoryOut(List<WcabCellInventoryInoutDetailForm> list, Long wcabCellInventoryInoutId, String deviceCode, WcabCellInventoryInout.BusinessType businessType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        WcabUseInventoryInout useInventoryInout = new WcabUseInventoryInout();
        String code = dynamicService.getDayNextCode("cab_use_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        useInventoryInout.setCode("OU-" + day + "-" + code);
        useInventoryInout.setDay(Integer.valueOf(day));
        useInventoryInout.setNo(Integer.valueOf(code));
        useInventoryInout.setCreator(JwtUtils.getLoginUserId());
        useInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        useInventoryInout.setInoutType(WcabUseInventoryInout.InoutType.out);
        useInventoryInout.setBusinessId(wcabCellInventoryInoutId);
        useInventoryInout.setDeviceCode(deviceCode);
        useInventoryInout.setCellInventoryInoutId(wcabCellInventoryInoutId);
        useInventoryInout.setBusinessType(WcabUseInventoryInout.BusinessType.jsonCreator(businessType.name()));
        useInventoryInout.setRemark(useInventoryInout.getBusinessType() != null ? useInventoryInout.getBusinessType().getDesc() : "");
//        useInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        useInventoryInout.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        useInventoryInout.setDeviceCode(deviceCode);
        if (StringUtils.isBlank(deviceCode)) {
            useInventoryInout.setDeviceCode(list.get(0).getDeviceCode());
        }
        inventoryInoutService.save(useInventoryInout);
        saveDetail(list,useInventoryInout.getId(),UseInventoryInout.Type.out.name(),businessType.name(),deviceCode,null,wcabCellInventoryInoutId,null, StorageInventoryInout.BusinessDetailType.jsonCreator(businessType.name()));
    }

    @Transactional
    void saveDetail(List<WcabCellInventoryInoutDetailForm> list,Long inventoryInoutId,String inOutTypeName,String businessTypeName,String deviceCode,String orderCode,Long cellInventoryInoutId,Long storageInventoryInoutId,StorageInventoryInout.BusinessDetailType businessDetailType){
//        List<String> labelCodes=new ArrayList<>();
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        if (CollectionUtils.isNotEmpty(list)){
            for (WcabCellInventoryInoutDetailForm wcabUseInventoryInoutDetailForm:list){
                WcabUseInventoryInoutDetail wcabUseInventoryInoutDetail=new WcabUseInventoryInoutDetail();
                BeanUtils.copyProperties(wcabUseInventoryInoutDetailForm,wcabUseInventoryInoutDetail);
                wcabUseInventoryInoutDetail.setId(null);
                wcabUseInventoryInoutDetail.setCreator(creator);
                wcabUseInventoryInoutDetail.setCreatorName(creatorName);
                wcabUseInventoryInoutDetail.setType(WcabUseInventoryInoutDetail.Type.jsonCreator(inOutTypeName));
                wcabUseInventoryInoutDetail.setBusinessType(WcabUseInventoryInoutDetail.BusinessType.jsonCreator(businessTypeName));
                wcabUseInventoryInoutDetail.setInoutId(inventoryInoutId);
                List<WcabUseInventoryProduct> skuInventoryList=inventoryProductService.list(new QueryWrapper<WcabUseInventoryProduct>().eq("sku_code",wcabUseInventoryInoutDetailForm.getSkuCode()));

                if (UseInventoryInout.Type.out.name().equals(inOutTypeName)||
                        UseInventoryInout.Type.returned.name().equals(inOutTypeName)){

                    ProductDetailVO productDetailVO=productDetailService.getProductDetailBySkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                    ProductDetail.InventoryUnitType inventoryUnitType=null;
                    if (productDetailVO!=null){
                        inventoryUnitType=productDetailVO.getInventoryUnitType();
                    }

                    List<WcabUseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<WcabUseInventoryUser>().eq("sku_code",wcabUseInventoryInoutDetailForm.getSkuCode()).eq("creator",wcabUseInventoryInoutDetailForm.getCreator()));
//                    List<WcabUseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<WcabUseInventoryUser>().eq("id",wcabUseInventoryInoutDetailForm.getId()));
//                    List<UseInventoryKnife> skuInventoryKnifeList=useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id",wcabUseInventoryInoutDetailForm.getId()));
//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException("未找到SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
//                    }else{
                        /**
                        Integer quantity=wcabUseInventoryInoutDetailForm.getQuantity();
                        BigDecimal weigth=wcabUseInventoryInoutDetailForm.getWeight();
                        if (quantity>0){
                            quantity=-1*quantity;
                        }
                        if (weigth.doubleValue()>0){
                            weigth=weigth.multiply(BigDecimal.valueOf(-1));
                        }

                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;
                        BigDecimal currentWeigth=skuInventoryUserList.get(0).getWeight();
                        BigDecimal newWeight=currentWeigth.add(weigth);
                        if (newQuantity<0){
                            throw new BusinessException("SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                        }
                        if (newWeight.doubleValue()<0){
                            throw new BusinessException("SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                        }

                        WcabUseInventoryUser useInventoryUser=new WcabUseInventoryUser();
                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        useInventoryUser.setQuantity(newQuantity);
                        useInventoryUser.setWeight(newWeight);
                        if (newWeight.doubleValue()==0){
                            inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                        }else{
                            inventoryUserService.updateById(useInventoryUser);
                        }

                        wcabUseInventoryInoutDetail.setQuantity(quantity);
                        wcabUseInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        wcabUseInventoryInoutDetail.setQuantityAfter(newQuantity);
                        wcabUseInventoryInoutDetail.setQuantity(quantity);
                        wcabUseInventoryInoutDetail.setWeightCurrent(currentWeigth);
                        wcabUseInventoryInoutDetail.setWeightAfter(newWeight);
                        wcabUseInventoryInoutDetail.setWeight(weigth);
                        wcabUseInventoryInoutDetail.setCreator(creator);
                        wcabUseInventoryInoutDetail.setCreatorName(creatorName);
//                        wcabUseInventoryInoutDetail.setModifier(creator);
//                        wcabUseInventoryInoutDetail.setModifierName(creatorName);
                        baseMapper.insert(wcabUseInventoryInoutDetail);*/
//                    }
                    Integer quantity=wcabUseInventoryInoutDetailForm.getQuantity();
                    BigDecimal weight=wcabUseInventoryInoutDetailForm.getWeight();
                    if (quantity>0){
                        quantity=-1*quantity;
                    }
                    if (weight.doubleValue()>0){
                        weight=weight.multiply(BigDecimal.valueOf(-1));
                    }

//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException("未找到SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
//                    }else{
                    if (skuInventoryList.size()>0){


                        Integer currentQuantity=skuInventoryList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;
                        BigDecimal currentWeight=skuInventoryList.get(0).getWeight();
                        BigDecimal newWeight=currentWeight.add(weight);
                        if (ProductDetail.InventoryUnitType.quantity.equals(inventoryUnitType)){
                            if (newQuantity<0){
//                                throw new BusinessException("SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的产品在用库存不足");
//                            newQuantity=0;
                            }
                        }else{
                            if (newWeight.doubleValue()<0){
//                                throw new BusinessException("SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的产品在用库存不足");
//                            newQuantity=0;
                            }
                        }


                        WcabUseInventoryProduct wcabUseInventoryProduct=new WcabUseInventoryProduct();
                        wcabUseInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        wcabUseInventoryProduct.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        wcabUseInventoryProduct.setQuantity(newQuantity);
                        wcabUseInventoryProduct.setWeight(newWeight);
                        if (ProductDetail.InventoryUnitType.quantity.equals(inventoryUnitType)){
                            if (newQuantity<=0){
                                inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            }else{
                                inventoryProductService.updateById(wcabUseInventoryProduct);
                            }
                        }else{
                            if (newWeight.doubleValue()<=0){
                                inventoryProductService.removeById(skuInventoryList.get(0).getId());
                            }else{
                                inventoryProductService.updateById(wcabUseInventoryProduct);
                            }
                        }




                        wcabUseInventoryInoutDetail.setQuantity(quantity);
                        wcabUseInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        wcabUseInventoryInoutDetail.setQuantityAfter(newQuantity);
                        wcabUseInventoryInoutDetail.setQuantity(quantity);
                        wcabUseInventoryInoutDetail.setWeightCurrent(currentWeight);
                        wcabUseInventoryInoutDetail.setWeightAfter(newWeight);
                        wcabUseInventoryInoutDetail.setWeight(weight);
                        wcabUseInventoryInoutDetail.setCreator(creator);
                        wcabUseInventoryInoutDetail.setCreatorName(creatorName);
//                        wcabUseInventoryInoutDetail.setModifier(creator);
//                        wcabUseInventoryInoutDetail.setModifierName(creatorName);
                        baseMapper.insert(wcabUseInventoryInoutDetail);

                    }
                    if (skuInventoryUserList.size()>0){
                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+quantity;
                        BigDecimal currentWeight=skuInventoryUserList.get(0).getWeight();
                        BigDecimal newWeight=currentWeight.add(weight);
                        if (ProductDetail.InventoryUnitType.quantity.equals(inventoryUnitType)){
                            if (newQuantity<0){
//                                throw new BusinessException("SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的产品在用库存不足");
//                            newQuantity=0;
                            }
                        }else{
                            if (newWeight.doubleValue()<0){
//                                throw new BusinessException("SKU["+wcabUseInventoryInoutDetailForm.getSkuCode()+"]的产品在用库存不足");
//                            newQuantity=0;
                            }
                        }


                        WcabUseInventoryUser wcabUseInventoryUser=new WcabUseInventoryUser();
                        wcabUseInventoryUser.setId(skuInventoryList.get(0).getId());
//                        wcabUseInventoryUser.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        wcabUseInventoryUser.setQuantity(newQuantity);
                        wcabUseInventoryUser.setWeight(newWeight);
                        if (ProductDetail.InventoryUnitType.quantity.equals(inventoryUnitType)){
                            if (newQuantity<=0){
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            }else{
                                inventoryUserService.updateById(wcabUseInventoryUser);
                            }
                        }else{
                            if (newWeight.doubleValue()<=0){
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            }else{
                                inventoryUserService.updateById(wcabUseInventoryUser);
                            }
                        }
                    }

//                    }
                }else if(UseInventoryInout.Type.in.name().equals(inOutTypeName)){
                    List<WcabUseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<WcabUseInventoryUser>().eq("sku_code",wcabUseInventoryInoutDetailForm.getSkuCode()).eq("creator",creator));

//                    Integer quantity=wcabUseInventoryInoutDetailForm.getQuantity();
                    if (wcabUseInventoryInoutDetailForm.getQuantity()<0){
                        throw new BusinessException("领取数量参数异常");
                    }
                    if (skuInventoryList.size()==0){
                        Integer currentQuantity=0;
                        Integer newQuantity=currentQuantity+wcabUseInventoryInoutDetailForm.getQuantity();
                        BigDecimal newWeight=wcabUseInventoryInoutDetailForm.getWeight();
                        WcabUseInventoryProduct wcabUseInventoryProduct=new WcabUseInventoryProduct();
                        wcabUseInventoryProduct.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        wcabUseInventoryProduct.setQuantity(newQuantity);
                        wcabUseInventoryProduct.setDeviceCode(deviceCode);
                        wcabUseInventoryProduct.setWeight(newWeight);
                        inventoryProductService.save(wcabUseInventoryProduct);

                        wcabUseInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        wcabUseInventoryInoutDetail.setQuantityAfter(newQuantity);
                        wcabUseInventoryInoutDetail.setQuantity(wcabUseInventoryInoutDetailForm.getQuantity());
                        wcabUseInventoryInoutDetail.setWeightCurrent(BigDecimal.valueOf(0));
                        wcabUseInventoryInoutDetail.setWeightAfter(newWeight);
                        wcabUseInventoryInoutDetail.setWeight(wcabUseInventoryInoutDetailForm.getWeight());
                        baseMapper.insert(wcabUseInventoryInoutDetail);
                    }else{

                        Integer currentQuantity=skuInventoryList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+wcabUseInventoryInoutDetailForm.getQuantity();
                        BigDecimal currentWeight=skuInventoryList.get(0).getWeight();
                        BigDecimal newWeigth=currentWeight.add(wcabUseInventoryInoutDetailForm.getWeight());

                        WcabUseInventoryProduct wcabUseInventoryProduct=new WcabUseInventoryProduct();
                        wcabUseInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        wcabUseInventoryProduct.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        wcabUseInventoryProduct.setQuantity(newQuantity);
                        wcabUseInventoryProduct.setWeight(newWeigth);
                        inventoryProductService.updateById(wcabUseInventoryProduct);

                        wcabUseInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        wcabUseInventoryInoutDetail.setQuantityAfter(newQuantity);
                        wcabUseInventoryInoutDetail.setQuantity(wcabUseInventoryInoutDetailForm.getQuantity());
                        wcabUseInventoryInoutDetail.setWeightCurrent(currentWeight);
                        wcabUseInventoryInoutDetail.setWeightAfter(newWeigth);
                        wcabUseInventoryInoutDetail.setWeight(wcabUseInventoryInoutDetailForm.getWeight());
                        baseMapper.insert(wcabUseInventoryInoutDetail);
                    }

                    if (skuInventoryUserList.size()==0){
                        WcabUseInventoryUser useInventoryUser=new WcabUseInventoryUser();
                        useInventoryUser.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        useInventoryUser.setQuantity(wcabUseInventoryInoutDetailForm.getQuantity());
                        useInventoryUser.setWeight(wcabUseInventoryInoutDetailForm.getWeight());
                        useInventoryUser.setCreator(creator);
                        useInventoryUser.setCreatorName(creatorName);
                        useInventoryUser.setDeviceCode(deviceCode);
//                    useInventoryUser.setOrderCode(orderCode);
                        useInventoryUser.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryUser.setCabCode(wcabUseInventoryInoutDetailForm.getCabCode());
                        useInventoryUser.setSpaceCode(wcabUseInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUser.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryUser.setUseInventoryInoutDetailId(wcabUseInventoryInoutDetail.getId());
                        inventoryUserService.save(useInventoryUser);
                    }else{
                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
                        Integer newQuantity=currentQuantity+wcabUseInventoryInoutDetailForm.getQuantity();
                        BigDecimal currentWeight=skuInventoryUserList.get(0).getWeight();
                        BigDecimal newWeigth=currentWeight.add(wcabUseInventoryInoutDetailForm.getWeight());

                        WcabUseInventoryUser useInventoryUser=new WcabUseInventoryUser();
                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        wcabUseInventoryProduct.setSkuCode(wcabUseInventoryInoutDetailForm.getSkuCode());
                        useInventoryUser.setQuantity(newQuantity);
                        useInventoryUser.setWeight(newWeigth);
                        inventoryUserService.updateById(useInventoryUser);
                    }



                }else{
                    throw new BusinessException("出入库参数类型异常");
                }

            }
        }else{
            throw new BusinessException("未提交领用/存放刀具数据");
        }
//        return labelCodes;
    }
}
